package com.itheima.service.db.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.domain.db.*;
import com.itheima.mapper.*;
import com.itheima.service.db.TestSoulService;
import com.itheima.vo.UserSoulReportVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@DubboService
public class TestSoulServiceImpl implements TestSoulService {

    @Autowired
    private TestSoulQuestionMapper testSoulQuestionMapper;

    @Autowired
    private TestSoulContentMapper testSoulContentMapper;

    @Autowired
    private TestSoulOptionMapper testSoulOptionMapper;

    @Autowired
    private UserSoulReportMapper userSoulReportMapper;

    @Autowired
    private CoverMapper coverMapper;

    @Autowired
    private ConclusionMapper conclusionMapper;

    @Autowired
    private DimensionsMapper dimensionsMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    //查询所有的测灵魂试卷
    @Override
    public List<TestSoulQuestion> findAll(Long userId) {
        List<TestSoulQuestion> list = testSoulQuestionMapper.selectList(null);

        if (CollectionUtil.isNotEmpty(list)) {
            for (TestSoulQuestion question : list) {
                //根据内容id获取获取问题
                List<TestSoulContent> contentList = testSoulContentMapper.selectList(null);

                for (TestSoulContent content : contentList) {
                    //根据选项id获取选项
                    TestSoulOption option = testSoulOptionMapper.findById(content.getOptionId());

                    //调用方法将其转成List<Map<String, String>>对象
                    List<Map<String, String>> mapList =  changeToMap(option);

                    content.setOptions(mapList);
                }

                //查看用户这份测试卷是否做过
                LambdaQueryWrapper<UserSoulReport> qw = new LambdaQueryWrapper<>();
                qw.eq(UserSoulReport::getUserId,userId).eq(UserSoulReport::getQuestionId,question.getId());
                UserSoulReport report = userSoulReportMapper.selectOne(qw);
                if (report != null){
                    question.setReportId(report.getId().toString());
                }

                question.setQuestions(contentList);



            }
        }
        return list;
    }

    //根据评分保存报告
    @Override
    public String saveUserSoulReport(Long userId, Integer score) {
        LambdaQueryWrapper<UserSoulReport> qw = new LambdaQueryWrapper<>();
        qw.eq(UserSoulReport::getUserId,userId);

        //查询之前是否做过这套试卷
        UserSoulReport report = userSoulReportMapper.selectOne(qw);
        if (report == null){
            //没做过，插入
            report = new UserSoulReport();
            //补充相关数据
            report.setCreated(DateUtil.formatDate(new Date()));
            report.setUserId(userId);
            setProperties(report,score);
            userSoulReportMapper.insert(report);

            return report.getId().toString();
        }

        //做过，重新设置属性
        setProperties(report,score);
        //更新报告
        userSoulReportMapper.updateById(report);


        return report.getId().toString();
    }

    private void setProperties(UserSoulReport report, Integer score) {
        if (score < 21){
            report.setConclusionType(1);
            report.setDimensionsType(1);
            report.setSimilarUserId("1,2,3");
            report.setCover(1);
            report.setQuestionId(1);
        }else if (score < 40 && score >= 21){
            report.setConclusionType(2);
            report.setDimensionsType(2);
            report.setSimilarUserId("1,2,3");
            report.setQuestionId(1);
            report.setCover(2);
        } else if (score < 55 && score >= 40){
            report.setConclusionType(3);
            report.setDimensionsType(3);
            report.setSimilarUserId("1,2,3");
            report.setQuestionId(1);
            report.setCover(3);
        }else {
            report.setConclusionType(4);
            report.setDimensionsType(4);
            report.setSimilarUserId("1,2,3");
            report.setQuestionId(1);
            report.setCover(4);
        }
    }

    /**
     * 获取测试报告
     * @param reportId
     * @return
     */
    @Override
    public UserSoulReportVo getReport(Integer reportId) {

        UserSoulReportVo vo = new UserSoulReportVo();

        UserSoulReport report = userSoulReportMapper.selectById(reportId);
        //封装封面
        vo.setCover(coverMapper.selectById(report.getCover()).getCover());
        //封装描述
        vo.setConclusion(conclusionMapper.selectById(report.getConclusionType()).getConclusion());

        //封装性格
        Dimensions dimensions = dimensionsMapper.selectById(report.getDimensionsType());
        List<Dimensions> dimensionsList = new ArrayList<>();
        String[] values = dimensions.getValue().split(",");
        Dimensions dm = new Dimensions();
        dm.setKey("外向");
        dm.setValue(values[0]);
        dimensionsList.add(dm);
        dm = new Dimensions();
        dm.setKey("判断");
        dm.setValue(values[1]);
        dimensionsList.add(dm);
        dm = new Dimensions();
        dm.setKey("抽象");
        dm.setValue(values[2]);
        dimensionsList.add(dm);
        dm = new Dimensions();
        dm.setKey("理性");
        dm.setValue(values[3]);
        dimensionsList.add(dm);

        vo.setDimensions(dimensionsList);


        //封装相似用户信息
        List<UserInfo> userInfos = new ArrayList<>();
        String ids = report.getSimilarUserId();
        if (ids != null && ids.length() != 0){
            String[] similarIds = ids.split(",");

            for (String similarId : similarIds) {
                UserInfo userInfo = userInfoMapper.selectById(Long.valueOf(similarId));
                userInfos.add(userInfo);
            }


        }

        vo.setSimilarYou(userInfos);



        return vo;
    }

    private List<Map<String, String>> changeToMap(TestSoulOption option) {
        List<Map<String, String>>  mapList = new ArrayList<>();

        String[] options = option.getOption().split(",");
        char i = 'A';

        for (String op : options) {
            Map<String, String> map =  new HashMap<>();
            map.put("id", String.valueOf(i));
            map.put("option",op);
            mapList.add(map);
            i++;
        }

        return mapList;
    }
}
